package com.medical.wechat.service.impl;


import com.medical.common.CustomizeException;
import com.medical.common.Http;
import com.medical.wechat.mapper.WechatAccountMapper;
import com.medical.wechat.mapper.WechatMenuMapper;
import com.medical.wechat.model.WechatAccount;
import com.medical.wechat.model.WechatMenu;
import com.medical.wechat.service.WechatMenuService;
import com.medical.wechat.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;

import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;

@SuppressWarnings("SpringJavaAutowiringInspection")
@Service("wechatMenuService")
public class WechatMenuServiceImpl implements WechatMenuService {

	private static String WECHAT_MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";

	@Autowired
	private WechatMenuMapper menuMapper;
	
	@Autowired
	private WechatAccountMapper wechatAccountMapper;
	@Autowired
	private WechatMenuMapper wechatMenuMapper;


	@Override
	public List<WechatMenu> selectMenuByAccountId(String accountId) {
		List<WechatMenu> menuList = findByAccountId(accountId);
		List<WechatMenu> menuList1=new ArrayList<>();
		for(WechatMenu wechatMenu : menuList){
			String parentId = wechatMenu.getParentId();
			String parentName = "";

			if(findById(parentId) != null){ //如果有父级
				parentName = findById(parentId).getName();
			} else {
				parentName = "无父级菜单";
			}
			wechatMenu.setParentName(parentName);
			menuList1.add(wechatMenu);
		}
		return menuList1;
	}

	public List<WechatMenu> findByAccountId(String accountId) {
		return menuMapper.findByAccountId(accountId);
	}
	public WechatMenu findById(String id) {
		return menuMapper.findById(id);
	}
	public void createWechatMenu(WechatMenu wechatMenu){
		if(wechatMenu!=null){
			if(StringUtils.isEmpty(wechatMenu.getParentId())) {
				throw new CustomizeException("parentid不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getName())) {
				throw new CustomizeException("name不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getType())) {
				throw new CustomizeException("type不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getKey())) {
				throw new CustomizeException("key不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getSort())) {
				throw new CustomizeException("sort不能为空");
			}
			if(wechatMenu.getParentId()=="0"){//如果是父级
				List<WechatMenu> list = selectByParentId(wechatMenu.getParentId());
				if(list.size()<3){
					wechatMenuMapper.createWechatMenu(wechatMenu);
				}else{
					throw new CustomizeException("父级菜单栏的栏数已满");
				}
			}else{
				List<WechatMenu> list = selectByParentId(wechatMenu.getParentId());
				if(list.size()<5){
					wechatMenuMapper.createWechatMenu(wechatMenu);
				}else{
					throw new CustomizeException("子级菜单栏的栏数已满");
				}
			}
		}else{
			throw new CustomizeException("信息不能为空");
		}

	}
	public List<WechatMenu> selectByParentId(String parentId){

		return wechatMenuMapper.findByParentId(parentId);
	}
	public void updateById(WechatMenu wechatMenu) {
		if (wechatMenu != null) {
			if(StringUtils.isEmpty(wechatMenu.getParentId())) {
				throw new CustomizeException("parentid不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getName())) {
				throw new CustomizeException("name不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getType())) {
				throw new CustomizeException("type不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getKey())) {
				throw new CustomizeException("key不能为空");
			}
			if(StringUtils.isEmpty(wechatMenu.getSort())) {
				throw new CustomizeException("sort不能为空");
			}
			menuMapper.updateById(wechatMenu);
		} else
			throw new CustomizeException("信息不能为空");
		}
	public void deleteWechatMenuById(String id){
		wechatMenuMapper.deleteWechatMenuById(id);
	}

	public String generateWechatMenu(String accountId) {

		Map<String, Object> wechatMenuMap = new HashMap<String, Object>();
		List<Map<String, Object>> wechatMenuMapList = new ArrayList<Map<String, Object>>();

		List<WechatMenu> menuList = menuMapper.findFristMenu(accountId);//返回全部父级菜单集合（根据sort排序）
		for(WechatMenu menu : menuList){

			String id = menu.getId();
			String name = menu.getName();
			String type = menu.getType();
			String key = menu.getKey();

			Map<String, Object> menuMap = new HashMap<String, Object>();

			List<WechatMenu> parentMenuList = menuMapper.findByParentId(id);//返回全部子级菜单集合（根据sort排序）
			if(parentMenuList.size() > 0){

				List<Map<String, Object>> subMenuMapList = new ArrayList<Map<String, Object>>();

				for(WechatMenu subMenu : parentMenuList){

					String subName = subMenu.getName();
					String subType = subMenu.getType();
					String subKey = subMenu.getKey();

					subMenuMapList.add(createSubMap(subName, subType, subKey));
				}

				menuMap.put("name", name);
				menuMap.put("sub_button", subMenuMapList);

			} else {

				menuMap.put("name", name);
				menuMap.put("type", type);
				if(type.equals("view")){
					menuMap.put("url", key);
				} else {
					menuMap.put("key", key);
				}

			}

			wechatMenuMapList.add(menuMap);
		}

		wechatMenuMap.put("button", wechatMenuMapList);

		String json = JSON.toJSONString(wechatMenuMap, true);

		String accessToken = wechatAccountMapper.findById(accountId).getAccessToken();

		String result = Http.post(WECHAT_MENU_CREATE_URL + accessToken, json);

		Map<String,Object> resultMap = (Map<String,Object>)JSON.parse(result);

		return resultMap.get("errmsg").toString();
	}

	private Map<String,Object> createSubMap(String title, String type, String key){
		Map<String,Object> m = new HashMap<String, Object>();
		m.put("type", type);
		m.put("name",title);
		if("view".equals(type)){
			m.put("url", key);
		}else if("click".equals(type)){
			m.put("key", key);
		}else {
			m.put("key", key);
		}

		return m;
	}

	public String generateDefaultMenu(String accountId, String userId) {

		String baseUrl = Constants.WEB_URL + "/medicalO2O";

		Map<String,Object> m = new HashMap<String, Object>();
		List<Map<String,Object>> buttons = new ArrayList<Map<String,Object>>();

		WechatAccount wechatAccount = wechatAccountMapper.findById(accountId);
		String accessToken = wechatAccount.getAccessToken();
		String appId = wechatAccount.getAppId();

		/**
		 * 呵护一生
		 */
		Map<String,Object> hehuMap = new HashMap<String, Object>();
		hehuMap.put("name", "家庭医生");
		List<Map<String,Object>> hehuSub = new ArrayList<Map<String,Object>>();
		//个人中心
		hehuSub.add(createSubMap("个人中心", "view", createAuth2Url("", "wechatUserCenter", appId, accountId)));
		//会员系统
//		hehuSub.add(createSubMap("家庭医生服务", "view", createAuth2Url("findServicePackage", "account", appId)));
		//健康管理
//		hehuSub.add(createSubMap("健康管理", "view", createAuth2Url("", "healthManager", appId)));
		//地图导航
		hehuSub.add(createSubMap("地图导航", "click", Constants.LOCATION));

		hehuMap.put("sub_button", hehuSub);
		buttons.add(hehuMap);

		/**
		 * 就诊
		 */
		Map<String,Object> cureMap = new HashMap<String, Object>();
		cureMap.put("name", "就诊");
		List<Map<String,Object>> cureSub = new ArrayList<Map<String,Object>>();
		cureSub.add(createSubMap("我的预约", "view", createAuth2Url("findMyAppo", "wechatBook", appId, accountId)));
		//我的预约
		cureSub.add(createSubMap("预约挂号", "view", createAuth2Url("", "wechatBook", appId, accountId)));
		//添加家人
		cureSub.add(createSubMap("添加家人", "view", createAuth2Url("findAddPatient", "wechatBook", appId, accountId)));
		//病情反馈
		cureSub.add(createSubMap("病情反馈", "view", createAuth2Url("choosePatient", "wechatQuestion", appId, accountId)));

		cureMap.put("sub_button", cureSub);
		buttons.add(cureMap);

		/**
		 * 资讯服务
		 */
		Map<String,Object> infoMap = new HashMap<String, Object>();
		infoMap.put("name", "资讯服务");
		List<Map<String,Object>> infoSub = new ArrayList<Map<String,Object>>();
		//患者资讯
		infoSub.add(createSubMap("患者咨询", "click", Constants.SICK_KEY));
		//app下载
		infoSub.add(createSubMap("app下载", "view", baseUrl+"/wechatInfo/download"));
		//最新班表
		infoSub.add(createSubMap("最新班表", "view", Constants.BAN_LIST_ADDRESS));
		//关于我们
		infoSub.add(createSubMap("关于我们", "view", baseUrl+"/wechatInfo/home"));
		//健康资讯--查看历史消息
		infoSub.add(createSubMap("健康资讯", "view", "http://mp.weixin.qq.com/mp/getmasssendmsg?__biz=MzAxMjA5OTMwMA==#wechat_webview_type=1&wechat_redirect"));

		infoMap.put("sub_button", infoSub);
		buttons.add(infoMap);

		m.put("button", buttons);

		String json = JSON.toJSONString(m, true);

		String result = Http.post(WECHAT_MENU_CREATE_URL + accessToken, json);

		Map<String, Object> resultMap = (Map<String,Object>)JSON.parse(result);

		saveGenerateDefaultMenuInfo(buttons, accountId, userId);

		return resultMap.get("errmsg").toString();
	}
	private String createAuth2Url(String forword, String root, String appId, String accountId){
		try{
			StringBuffer authUrl=new StringBuffer()
					.append("https://open.weixin.qq.com/connect/oauth2/authorize?")
					.append("appid=").append(appId)
					.append("&response_type=code")
					.append("&scope=snsapi_base")
					.append("&redirect_uri=");

			StringBuffer redirectUri=new StringBuffer()
					.append(Constants.WEB_URL).append("/medicalO2O/wechat/forword/").append(root);

			StringBuffer sb = new StringBuffer()
					.append(authUrl.toString())
					.append(URLEncoder.encode(redirectUri.toString(), "utf-8"))
					.append("&state=").append(forword)
					.append("_").append(accountId)
					.append("#wechat_redirect");

			return sb.toString();
		}catch(Exception e){
			return "";
		}
	}
	private void saveGenerateDefaultMenuInfo(List<Map<String,Object>> mapList, String accountId, String userId){

		//删除该公众号的菜单信息
		menuMapper.deleteByAccountId(accountId);

		int i = 1;
		for(Map<String, Object> map : mapList){

			WechatMenu wechatMenu = new WechatMenu();
			String parentId = UUID.randomUUID().toString();
			String parentMenuName = map.get("name").toString();

			//创建父菜单
			wechatMenu.setId(parentId);
			wechatMenu.setAccountId(accountId);
			wechatMenu.setParentId("0");
			wechatMenu.setName(parentMenuName);
			wechatMenu.setType("none");
			wechatMenu.setKey(null);
			wechatMenu.setSort(i);
			wechatMenu.setCreatedBy(userId);
			wechatMenu.setCreatedTime(new Timestamp(System.currentTimeMillis()));
			menuMapper.createWechatMenu(wechatMenu);

			List<Map<String,Object>> subMenuList = (List<Map<String, Object>>) map.get("sub_button");
			int j = 0;
			for(Map<String,Object> subMenu : subMenuList){

				WechatMenu wechatSubMenu = new WechatMenu();

				String type = subMenu.get("type").toString();
				String subMenuName = subMenu.get("name").toString();

				String key = null;
				if("view".equals(type)){
					key = subMenu.get("url").toString();
				}else if("click".equals(type)){
					key = subMenu.get("key").toString();
				}else {
					key = subMenu.get("key").toString();
				}

				//创建子菜单
				wechatSubMenu.setId(UUID.randomUUID().toString());
				wechatSubMenu.setAccountId(accountId);
				wechatSubMenu.setParentId(parentId);
				wechatSubMenu.setName(subMenuName);
				wechatSubMenu.setType(type);
				wechatSubMenu.setKey(key);
				wechatSubMenu.setSort(j);
				wechatSubMenu.setCreatedBy(userId);
				wechatSubMenu.setCreatedTime(new Timestamp(System.currentTimeMillis()));
				menuMapper.createWechatMenu(wechatSubMenu);

				j++;
			}

			i++;
		}

	}
	public String changeMenuToOAuth(String accountId, String root, String forword) {
		WechatAccount wechatAccount = wechatAccountMapper.findById(accountId);
		String appId = wechatAccount.getAppId();

		try{
			StringBuffer authUrl=new StringBuffer()
					.append("https://open.weixin.qq.com/connect/oauth2/authorize?")
					.append("appid=").append(appId)
					.append("&response_type=code")
					.append("&scope=snsapi_base")
					.append("&redirect_uri=");

			StringBuffer redirectUri=new StringBuffer()
					.append(Constants.WEB_URL).append("/medicalO2O/wechat/forword/").append(root);

			StringBuffer sb = new StringBuffer()
					.append(authUrl.toString())
					.append(URLEncoder.encode(redirectUri.toString(), "utf-8"))
					.append("&state=").append(forword)
					.append("_").append(accountId)
					.append("#wechat_redirect");

			return sb.toString();
		}catch(Exception e){
			return "";
		}

	}
	}



